<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"
	import="java.io.IOException, models.Person, com.google.appengine.tools.remoteapi.RemoteApiInstaller, com.google.appengine.tools.remoteapi.RemoteApiOptions"%>
<%@ page import="com.googlecode.objectify.Objectify, com.googlecode.objectify.ObjectifyService, com.googlecode.objectify.Query, com.google.appengine.api.datastore.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> 
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Celestica Google Contacts</title>

<script language="JavaScript" type="text/javascript">
<!-- 
function changeNab(newPath){
	var curLoc = window.location.href;
	var newLoc = "";
	var pathLoc = curLoc.indexOf("&db=");
	if (pathLoc > -1){
		newLoc = curLoc.substring(0, pathLoc);
		pathLoc = curLoc.indexOf("&", pathLoc + 1);
		if (pathLoc == -1){
			newLoc = newLoc + "&db=" + newPath;
		} else {
			newLoc = newLoc + curLoc.substring(pathLoc) + "&db=" + newPath;
		}
	} else {
		newLoc = curLoc + "&db=" + newPath;
	}
	window.location=newLoc;
}

function checkForBackspace(curVal, key){
	//alert("checkForBackspace");
	if (key == "8"){
		setTimeout("doSearch();", 100);
	}
}

function doKeyPress(curVal, key) {
	//alert("doKeyPress");
	if(key =="13") {
		/* var trName = document.getElementById("nameChoicesTable").getElementsByTagName("tr")[0];
		if (trName.name){
			uName = trName.name;
		} else {
			uName = trName.className.substring(trName.className.indexOf(" ") + 1);
		}
		storeValue(uName); */
		return false;
	} else {		
		setTimeout("doSearch();", 100);
	}
}

function loadFirstPage() {
	try {
		// initialize variables
		var urlArray = document.location.href.split("/");

		URLPrefix = urlArray[0] + "//" + urlArray[2];

		// check to see if any parameters are being overridden from QueryString
		if (getURLParam("db") != "")
			dbPath = getURLParam("db");
		if (getURLParam("view") != ""){
			view = getURLParam("view");
		} else {
			view = "($VIMPeopleByLastName)"
		}
		if (getURLParam("columns") != ""){
			columns = getURLParam("columns").split(",");
		} else {
			columns = "0,2,3,5";
			columns = columns.split(",");
		}
		if (getURLParam("count") != ""){
			count = parseInt(getURLParam("count"), 10);
		} else {
			count = "16";
		}
		if (getURLParam("returnfield"))
			returnFieldName = getURLParam("returnfield");
		if (getURLParam("returncol") != "") {
			returnColumn = parseInt(getURLParam("returncol"), 10);
		} else {
			returnColumn = "1";
		}
		//alert(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&count=" + count);
		// get initial data set
		//var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&count=" + count, true);
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function nextPage() {
	try {
		// work out where the next page starts
		alert("step: 1");
		var lastMax = parseInt(results[results.length - 1].attributes[0].value, 10);
		alert("step: 2");
		var start = lastMax + 1;
		alert("step: 3");
		if (start > (viewTotalDocs - (count - 1))){
			alert("step: 4");
			start = viewTotalDocs - (count - 1);
		}
		// get the next page
		alert("step: 5");
		var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&start=" + start + "&count=" + count);
		alert("step: 6");
	}
	catch (e) {
		alert("step: 7");
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function previousPage() {
	try {
		// work out where the previous page starts
		var lastMin = parseInt(results[0].attributes[0].value, 10);
		var start = lastMin - count;
		if (start < 1) {
			start = 1;
		}
		// get the previous page
		var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&start=" + start + "&count=" + count);
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function lastPage() {
	try {
		// work out where the last page starts
		start = viewTotalDocs - (count - 1);

		// get the next page
		var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&start=" + start + "&count=" + count);
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function doSearch() {
	//alert("doSearch");
	try 	{
		var returnfield = getURLParam("returnfield");
		//alert("returnfield:" + returnfield);
		var pageNum = getURLParam("pageNum");
		//alert("pageNum:" + pageNum);
		var search = document.getElementById("search").value;
		//alert("search:" + search);
		if (search != "") {
			//var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&startkey=" + escape(search) + "&count=" + count);
			parent.location='/utils/contact_p.jsp?returnfield=' + returnfield + '&pageNum=' + pageNum + '&search=' + search;			
		} else {
			//var xmlDoc = doXMLHTTPGet(URLPrefix + "/" + dbPath + "/" + view + "?readviewentries&startkey=a&count=" + count);
		}
	}
	catch (e) {
		document.getElementById("namelist").innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function storeValue(newValue) {
	try {
		/* alert("newValue: " + newValue);
		alert("returnFieldName: " + returnFieldName);
		alert("fieldReturn.value: " + fieldReturn.value); */
		var fieldReturn = window.opener.document.getElementById(returnFieldName);
		if (fieldReturn == null){
			fieldReturn = eval("window.opener.document.forms[0]." + returnFieldName);
		}
		if (fieldReturn) {
			if (fieldReturn.type == "text" || fieldReturn.type == "hidden" || fieldReturn.type == "textarea") {
				fieldReturn.value = unescape(newValue);
			} else {
				fieldReturn.length = 1;
				var strReturn = unescape(newValue);
				fieldReturn.options[0].text = strReturn;
				fieldReturn.options[0].value = strReturn;
				fieldReturn.options[0].selected = true;
			}
		} else {
			throw("Could not get field \"" + returnFieldName + "\"");
		}
	}
	catch (e) {
		alert("There has been an error returning the selected values:\n\n" + e.message);
	}
	window.close();
}

function displayData(xmlDoc) {
	// get areas which we are going to write results into
	var namelist = document.getElementById("namelist");
	var countlist = document.getElementById("countlist");

	try {
		namelist.innerHTML = "Please Wait...";

		//Open the XML Document
		var root = xmlDoc.documentElement;
		results = root.getElementsByTagName("viewentry");

		//Get the toplevelentries value each time in case it changes
		viewTotalDocs = parseInt(root.attributes[0].value, 10);

		var strHTML = "<table width=\"100%\" id=\"nameChoicesTable\">";
		for (i=0; i<results.length; i++) {
			//Get the value which the row will return if clicked
			var returnText = getInnerText(results[i].getElementsByTagName("entrydata")[returnColumn]);

			//Write the tr tag
			if (i % 2 == 0){
				strHTML += "<tr class=\"normal1 " + escape(returnText) + "\" onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal1'\" name=" + escape(returnText) + " onClick=\"storeValue('" + escape(returnText) + "');\">";
			} else {
				strHTML += "<tr class=\"normal2 " + escape(returnText) + "\" onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal2'\" name=" + escape(returnText) + " onClick=\"storeValue('" + escape(returnText) + "');\">";
			}
			for (iCol=0; iCol < columns.length; iCol++) {
				//Write each cell of the current row
				var text;
				try {
					text = getInnerText(results[i].getElementsByTagName("entrydata")[parseInt(columns[iCol], 10)]);
				}
				catch (e) {
					text =+ e. message + " (" + e.name + ")";
				}
				strHTML += "<td>" + text + "</td>";
			}
			strHTML += "</tr>";
		}
		strHTML += "</table>";

		// output the document count details
		countlist.innerHTML = results[0].attributes[0].value + " to " + results[results.length - 1].attributes[0].value + " of " + viewTotalDocs + " records";

		// output the table HTML
		namelist.innerHTML = strHTML;
	}
	catch (e) {
		namelist.innerHTML = errormessage + e. message + " (" + e.name + ")";
	}
}

function doXMLHTTPGet(vurl) {
	var returnData = null;

	if (window.XMLHttpRequest) {
		// we are in a non-IE browser
		httpObj=new XMLHttpRequest()
	} else if (window.ActiveXObject) {
		// we are in IE
		httpObj=new ActiveXObject("Microsoft.XMLHTTP")
	}

	// return the XML document when it has finished loading
	httpObj.onreadystatechange = function() {
			if (httpObj.readyState==4) 	{
				if (httpObj.status==200) {
					displayData(httpObj.responseXML);
				} else 	{
					alert("Problem retrieving XML data:" + httpObj.statusText)
				}
			}
		}

	//Request the XML document
	httpObj.open("GET",vurl,true)
	httpObj.send(null)
}
/*
	getInnerText function courtesy of Martin Honnen
	http://www.thescripts.com/forum/threadedpost582930.html
*/
function getInnerText (node) {
	if (typeof node.textContent != 'undefined') {
		return node.textContent;
	} else if (typeof node.innerText != 'undefined') {
		return node.innerText;
	} else if (typeof node.text != 'undefined') {
		return node.text;
	} else {
		switch (node.nodeType) {
			case 3:
				break;
			case 4:
				return node.nodeValue;
				break;
			case 1:
				break;
			case 11:
				var innerText = '';
				for (var i = 0; i < node.childNodes.length; i++)
				{
					innerText += getInnerText(node.childNodes[i]);
				}
				return innerText;
				break;
			default:
				return '';
		}
	}
}
/*
	More on this function can be found at
	http://www.fclonline.com/Articles/GetURLParameterinJavascri.html
*/
function getURLParam(strParamName) {
	//Get a URL Parameter from the current location.href
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ){
		//var strQueryString = "&" + strHref.substr(strHref.indexOf("?") + 1).toLowerCase();
		var strQueryString = "&" + strHref.substr(strHref.indexOf("?") + 1)
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
			if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}
// -->
</script>

<script language="JavaScript" type="text/javascript">
<!-- 
document._domino_target = "_self";
function _doClick(v, o, t, h) {
  var form = document._NABPickerSingle;
  if (form.onsubmit) {
     var retVal = form.onsubmit();
     if (typeof retVal == "boolean" && retVal == false)
       return false;
  }
  var target = document._domino_target;
  if (o.href != null) {
    if (o.target != null)
       target = o.target;
  } else {
    if (t != null)
      target = t;
  }
  form.target = target;
  form.__Click.value = v;
  if (h != null)
    form.action += h;
  form.submit();
  return false;
}
// -->
</script>


</head>
<body onload="loadFirstPage();">

		<script language="javascript">
			/*
			 Configuration parameters which can be overridden
			 */
			var dbPath = "names.nsf"; //The default database to be used (can be overridden with the URL Param "db", e.g. "...html?db=mydir/mydb.nsf")
			var view = "($VIMPeople)"; //The default view to be used (can be overridden with the URL Param "view", e.g. "...html?view=myview")
			var columns = new Array("1", "2", "3", "0"); //The default columns which will be returned, and the order they will be displayed in
			//Can be overridden with the URL Param "columns" e.g. "...html?columns=1,2,3,4)
			var count = 10; //The default number of documents to return per page (can be overridden with the URL Param "count", e.g. "...html?count=20)
			var returnFieldName = null; //The fieldname which the selected value will be returned to (must be a plain text or textarea field)
			var returnColumn = 0; //The column from the view which will be returned to the returnFieldName
			/*
			 Global Variables
			 */

			var namesPicked = false;
			var results; // stores the xml returned from the view
			var viewTotalDocs; // stores the total number of docs in the view
			var URLPrefix; // stores the protocol and hostname (e.g. http://myhost)
			var aValues = new Array() // array of values to be written back
			var httpObj; // stores the XMLHTTPRequest
			var errormessage = "There has been an error displaying the data:<$tag_";
			// stores the error message prefix
			// Catch the user pressing return to submit searches

			if (!document.all) {
				window.captureEvents(Event.KEYPRESS);
				window.onkeypress = doKeyPress;
			}
		</script>

        <link href="/media/dataTables/demo_page.css" rel="stylesheet" type="text/css" />
        <link href="/media/dataTables/demo_table.css" rel="stylesheet" type="text/css" />
        <link href="/media/dataTables/demo_table_jui.css" rel="stylesheet" type="text/css" />
        <link href="/media/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />
        <link href="/media/themes/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" media="all" />
        <script src="/scripts/jquery.js" type="text/javascript"></script>
        <script src="/scripts/jquery.dataTables.min.js" type="text/javascript"></script>
        <script type="text/javascript">
        $(document).ready(function () {
            $("#contacts").dataTable({
                "sPaginationType": "full_numbers",
                "bJQueryUI": true
            });           
            
        });
        </script>

<h2>Google Contacts :</h2>
<div id="dt_example">
    <div id="container">
        <div id="demo_jui">
      <table id="contacts" class="display">
          <thead>
              <tr>
                  <th>Email ID</th>
                  <th>Name</th>
              </tr>
          </thead>
          <tbody>


<%
	RemoteApiOptions options = new RemoteApiOptions()
										.server("clswhitepages.appspot.com", 443)
										.credentials("srvan@celestica.com", "Sriniwas2fine");
	RemoteApiInstaller installer = new RemoteApiInstaller();
	String Email = "";
	String FullName = "";

	try {
		installer.install(options);	
		try {			
			Objectify ofy = ObjectifyService.begin();
			Query<Person>  personrec = ofy.query(Person.class);
			//Query<SolutionSubmission> rs = ofy.query(SolutionSubmission.class).filter("Status","Draft").filter("submittedBY",useremail);
			//DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			int cnt = 0;
			for ( Person f : personrec.fetch() ) {
				Email = f.getEMAIL();
				FullName = f.getEE_FULLNAME();

				if( Email != null ){
		       		out.println("<tr>");
		       		out.println("<td onClick=\"storeValue('" + Email + "');\">" + Email + "</td>");				
					out.println("<td onClick=\"storeValue('" + Email + "');\">" + FullName + "</td>");				
					out.println("</tr>");
				}
				cnt++;
				//if ( cnt > 20) break;
			}	       
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
	} catch (IOException e) {
		e.printStackTrace();
		// TODO Auto-generated catch block
	}
	finally {
        installer.uninstall();
	}	
%>

          </tbody>
      </table>
      </div>
    </div>
</div>

</body>
</html>